const fs = require('fs');
const Router = require("koa-router");
const path = require("path");
const router = new Router()
const request = require('request')

 fs.readdirSync(__dirname).forEach(file => {
  console.log('file',file)
  if(file !== 'index.js'){
    let r = require('./'+file)
    router.use(r.routes())
  }
 })

 const homePage = fs.readFileSync(path.join(__dirname, "../index.html"), "utf-8");
 router.get("/index", async (ctx) => {
  ctx.body = homePage;
});


function sendmess (appid, mess) {
  return new Promise((resolve, reject) => {
    request({
      method: 'POST',
      url: `http://api.weixin.qq.com/cgi-bin/message/custom/send?from_appid=${appid}`,
      body: JSON.stringify(mess)
    }, function (error, response) {
      if (error) {
        console.log('接口返回错误', error)
        reject(error.toString())
      } else {
        console.log('接口返回内容', response.body)
        resolve(response.body)
      }
    })
  })
}

router.all("/msgPush", async (ctx) => {
  console.log('ctx',ctx)
  const appid = ctx.request.header['x-wx-from-appid'] || ''
  const { ToUserName, FromUserName, MsgType, Content, CreateTime } = ctx?.request?.body
  console.log('推送接收的账号', ToUserName, '创建时间', CreateTime)
  return await sendmess(appid, {
    touser: FromUserName,
    msgtype: 'text',
    text: {
      content: '这是回复的消息'
    }
  })
});

 module.exports = router